package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@DubboService
public class VideoApiilmpl implements VideoApi{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Override
    public String save(Video video) {
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        Video save = mongoTemplate.save(video);
        return save.getId().toHexString();
    }

    @Override
    public List<Video> findMovementsByVids(List<Long> vids) {
        Query query = Query.query(Criteria.where("vid").in(vids));
      return mongoTemplate.find(query,Video.class);
    }

    @Override
    public List<Video> queryVideoList(int contns, Integer pagesize) {
        Query query = new Query().limit(pagesize).skip((contns-1)*pagesize).with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Video.class);
    }

    @Override
    public PageResult findbyids(Integer page, Integer pagesize, Long uid) {
        Query query =Query.query(Criteria.where("userId").is(uid));
        long count = mongoTemplate.count(query, Video.class);
        query.skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        System.out.println("------------");
        System.out.println(videos.toString());
        return new PageResult(page,pagesize,count,videos);
    }
}
